package com.ye.study.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {
    //方法一
/*    @Value("${thread.pool.corePoolSize}")
    private int coraPoolSize;
    @Value("${thread.pool.maxPoolSize}")
    private int maxPoolSize;
    @Value("${thread.pool.queueCapacity}")
    private int queueCapacity;
    @Value("${thread.pool.keepAliveSeconds}")
    private int keepAliveSenconds;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPool.setCorePoolSize(coraPoolSize);
        //最大线程数
        threadPool.setMaxPoolSize(maxPoolSize);
        //等待队列最大长度
        threadPool.setQueueCapacity(queueCapacity);
        //线程池允许的空闲时间
        threadPool.setKeepAliveSeconds(keepAliveSenconds);
        //异步方法内部线程
        threadPool.setThreadNamePrefix("spring默认线程池");
        //拒绝策略
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //任务完成时在关闭线程
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        //任务初始化
        threadPool.initialize();
        return threadPool;
    }*/
    //方法二
    @Autowired
    private ThreadPoolConfigProperties threadPoolConfigProperties;
    @Bean
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPool.setCorePoolSize(threadPoolConfigProperties.getCoraPoolSize());
        //最大线程数
        threadPool.setMaxPoolSize(threadPoolConfigProperties.getMaxPoolSize());
        //等待队列最大长度
        threadPool.setQueueCapacity(threadPoolConfigProperties.getQueueCapacity());
        //线程池允许的空闲时间
        threadPool.setKeepAliveSeconds(threadPoolConfigProperties.getKeepAliveSenconds());
        //异步方法内部线程
        threadPool.setThreadNamePrefix("spring默认线程池");
        //拒绝策略
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //任务完成时在关闭线程
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        //任务初始化
        threadPool.initialize();
        return threadPool;
    }

}
